<template>
  <view class="popup">
    <up-popup
      :show="$data.show"
      mode="bottom"
      :closeable="true"
      :closeOnClickOverlay="false"
      @close="close"
      @open="open"
    >
      <view class="content">
        <view class="content_img">
          <image :src="ImgLoginColor" />
        </view>
        <view class="content_box">
          <view class="width-p-100">
            <view class="content_box--title">欢迎使用青芒果到家</view>
            <view class="flex align-center margin-top-lg">
              <block v-if="!$data.next">
                <view class="check_img">
                  <image
                    v-if="!$data.check"
                    :src="ImgCheckUnGray"
                    @click="onCheck"
                  />
                  <image v-else :src="ImgCheckGreen" @click="onCheck" />
                </view>
                <view class="content_box--agreement" @tap="onCheck">
                  <text>
                    我已阅读并同意
                    <text
                      class="text-main-color"
                      @tap.stop="
                        onAgreement(configKeyEnum['青芒果到家服务协议'])
                      "
                    >
                      青芒果到家用户服务协议
                    </text>
                    和
                    <text
                      class="text-main-color"
                      @tap.stop="onAgreement(configKeyEnum['隐私协议'])"
                    >
                      青芒果到家隐私协议
                    </text>
                    和
                    <text
                      class="text-main-color"
                      @tap.stop="onAgreement(configKeyEnum['个人信息共享清单'])"
                    >
                      青芒果到家第三方信息共享清单
                    </text>
                  </text>
                </view>
              </block>
              <block v-else>
                <view class="text_phone">
                  <text v-if="!$data.bind">
                    为了给您更好的提供服务，青芒果到家小程序申请获取您的手机号并登录
                  </text>
                  <text v-else> 未获取到您的手机号，请手动添加绑定 </text>
                </view>
              </block>
            </view>
          </view>
          <view class="width-p-100" v-if="!$data.next">
            <view class="btn" @tap="onLogin">登录</view>
            <view class="un_login" @tap="unLogin">暂不登录</view>
          </view>
          <view v-else class="width-p-100">
            <view class="width-p-100" v-if="!$data.bind">
              <button
                open-type="getPhoneNumber"
                @getphonenumber="getPhoneNumber"
                class="btn u-reset-button"
              >
                手机号一键登录
              </button>
              <view class="un_login" @tap="unLogin">暂不登录</view>
            </view>
            <view class="width-p-100" v-else>
              <view class="text-bold margin-top">手机号</view>
              <view class="margin-top border-bottom-f0 padding-bottom-sm">
                <input v-model="$data.phone" placeholder="请输入手机号" />
              </view>
              <view class="text-bold margin-top-lg">验证码</view>
              <view class="sms margin-top border-bottom-f0 flex align-center">
                <view class="code padding-bottom-sm">
                  <input v-model="$data.code" placeholder="请输入验证码" />
                </view>
                <view class="time">
                  <text
                    class="text-main-color"
                    v-if="$data.timeNum === $data.NUM"
                    @tap="onSendSms"
                  >
                    获取验证码
                  </text>
                  <text v-else class="text-gray">
                    {{ $data.timeNum }}秒后重新获取
                  </text>
                </view>
              </view>
              <view class="padding-tb btns">
                <view class="btn btn_cancel flex-1" @tap="unLogin">取消</view>
                <view class="btn btn_save flex-1" @tap="onBind">立即绑定</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import {
  reactive,
  ref,
  nextTick,
  computed,
  onMounted,
  watch,
  watchEffect,
  getCurrentInstance,
} from "vue";
import { eventBus } from "../enums/eventBus";
import { ImgLoginColor, ImgCheckUnGray, ImgCheckGreen } from "../utils/iconMap";
import BasicConfig from "../utils/config";
import {
  useLogin,
  useOpenLogin,
  useSmsLogin,
  useWechatLogin,
} from "../hooks/useLogin";
import errorCode from "../utils/http/errorCode";
import { useGetUserInfo } from "../hooks/useUser";
import { useGetCurrentRouteStorage } from "../hooks/useStorage";
import { useGetConfig, useGetCurrentRoute } from "../hooks/useCommon";
import { configKeyEnum } from "../enums/common";
import { useRefundLog } from "../hooks/useSystem";
import { logClassify } from "../enums/system";
import { isDev } from "../utils/env";
import { smsSend } from "../api/Interface/app";
const Instance = getCurrentInstance();
const $vm = Instance?.appContext.config.globalProperties;
const $emits = defineEmits(["update:show", "close"]);
const $props = defineProps({});
const $data = reactive({
  show: isDev ? false : false, // 弹窗显隐
  check: false, // 协议勾选
  next: isDev ? false : false, // 用户未注册,需要授权手机号
  telCode: "",
  agree: false, // 用户同意登录
  bind: isDev ? false : false, // 手动绑定手机号
  phone: "",
  code: "",
  timeNum: 60, // 短信发送等待计时 60秒
  NUM: 60,
  timer: null,
});
const tabbar = [
  "pages/index/index",
  "pages/service/service",
  "pages/message/message",
  "pages/my/my",
];
const close = async () => {
  $data.show = false;
  $data.check = false;
  $data.next = false;
  $data.telCode = "";
  $emits("close");
  useOpenLogin(false);
  const route = useGetCurrentRoute();
  if (!$data.agree) return;
  if (tabbar.includes(route)) {
    uni.switchTab({
      // url: "/" + route,
      url: route,
    });
  } else {
    uni.redirectTo({
      // url: "/" + route,
      url: route,
    });
  }
};
const open = () => {
  $data.show = true;
};
const onCheck = () => {
  $data.check = !$data.check;
};
const onAgreement = (key) => {
  // 个人信息共享清单: "person_share",
  // 隐私协议: "privacy_agreement",
  // 青芒果到家服务协议: "work_service",
  useGetConfig({
    key,
    // isHtml: 0,
  }).then((res) => {
    console.log("key", res);
  });
};
const onLogin = async () => {
  if (!$data.check) {
    BasicConfig.toast("请阅读并勾选");
    return;
  }
	BasicConfig.loadToast();
	try {
  await useWechatLogin();
  const { code } = await useLogin();
  if (code === errorCode.success) {
    await useGetUserInfo();
    $data.agree = true;
    close();
  } else if (code === errorCode.nodata) {
    $data.agree = false;
    $data.next = true;
  }
	} catch (error) {
	}
  BasicConfig.loadHide(1000);
};
const unLogin = () => {
  $data.agree = false;
  uni.$emit(eventBus.login.popup, false);
  uni.navigateBack({
    delta: 1,
  });
  close();
};
const getPhoneNumber = async (e) => {
  console.log("获取手机号code", e);
  $data.telCode = e.detail.code;
  const { errMsg, iv, encryptedData } = e.detail;
  await useWechatLogin();
  const { code, msg, data } = await useLogin({
    telCode: $data.telCode,
    errMsg,
    iv,
    encryptedData,
  }).catch((err) => {
    useRefundLog({
      obj: err,
      getPhoneNumber: { errMsg, iv, encryptedData },
      type: "catch",
      classify: logClassify.LogPhone,
    });
  });
  BasicConfig.toast(msg);
  if (code === errorCode.success) {
    useRefundLog({
      obj: { code, msg, data },
      getPhoneNumber: { errMsg, iv, encryptedData },
      type: "success",
      classify: logClassify.LogPhone,
    });
    await useGetUserInfo();
    $data.agree = true;
    close();
  } else {
    useRefundLog({
      obj: { code, msg, data },
      getPhoneNumber: { errMsg, iv, encryptedData },
      type: "fail",
      classify: logClassify.LogPhone,
    });
    $data.bind = true;
  }
};
const onBind = async () => {
  if (!uni.$u.test.mobile($data.phone)) {
    BasicConfig.toast("请输入手机号码");
    return;
  }
  if (!$data.code) {
    BasicConfig.toast("请输入验证码");
    return;
  }
  await useWechatLogin();
  const { code, msg, data } = await useSmsLogin({
    phone: $data.phone,
    code: $data.code,
  }).catch((err) => {
    useRefundLog({
      obj: err,
      smsLoginParams: { phone: $data.phone, code: $data.code },
      type: "catch",
      classify: logClassify.PhoneSmsLogin,
    });
  });
  BasicConfig.toast(msg);
  if (code === errorCode.success) {
    useRefundLog({
      obj: { code, msg, data },
      smsLoginParams: { phone: $data.phone, code: $data.code },
      type: "success",
      classify: logClassify.PhoneSmsLogin,
    });
    await useGetUserInfo();
    close();
  } else {
    useRefundLog({
      obj: { code, msg, data },
      smsLoginParams: { phone: $data.phone, code: $data.code },
      type: "fail",
      classify: logClassify.PhoneSmsLogin,
    });
  }
};
const onSendSms = async () => {
  if (!uni.$u.test.mobile($data.phone)) {
    BasicConfig.toast("请输入手机号码");
    return;
  }
  smsSend({
    phone: $data.phone,
    type: "login",
    from: "user",
  }).then((res) => {
    BasicConfig.toast(res.msg);
    if (res.code === errorCode.success) {
      $data.timeNum = $data.NUM - 1;
      $data.timer = setInterval(() => {
        if ($data.timeNum > 0) {
          $data.timeNum--;
        } else {
          $data.timeNum = $data.NUM;
          clearInterval($data.timer);
          $data.timer = null;
        }
      }, 1000);
    }
  });
};
onMounted(() => {
  $data.timeNum = $data.NUM;
  if (isDev) $data.show = false;
  console.log("$data.show", $data.show);
  uni.$on(eventBus.login.popup, (e, message) => {
    const current = useGetCurrentRoute(); // 带参数全路径
    const currentPath = useGetCurrentRouteStorage();
    console.log("PopupLogin eventBus", e, current, currentPath, message);
    // currentPath == current && $data.show != e
    const route = current.split("?")[0];
    if (`/${currentPath}` == route && $data.show != e) {
      console.log("PopupLogin eventBus 已操作");
      $data.show = e;
    }
  });
});
watch(
  () => $data.show,
  (n, o) => {
    try {
      if (n) {
        uni.hideTabBar();
      } else {
        uni.showTabBar();
      }
    } catch (e) {
      console.log("PopupLogin watch $data.show catch", e);
    }
  },
  {
    immediate: true,
  }
);
// watchEffect();
</script>
<script>
// 小程序穿透
export default {
  options: { styleIsolation: "shared" },
};
</script>
<style lang="scss" scoped>
.popup {
  ::v-deep .u-popup__content {
    border-radius: 30rpx 30rpx 0 0 !important;
    // height: 52vh;
    height: auto;
  }
  .content {
    background: #ffffff;
    border-radius: 30rpx 30rpx 0 0;
    height: 100%;

    &_img {
      width: 100%;
      height: 425rpx;
      image {
        width: 100%;
        height: 100%;
        border-radius: 30rpx 30rpx 0 0;
      }
    }
    &_box {
      padding: 30rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      height: calc(100% - 425rpx);
      &--title {
        font-size: 42rpx;
        font-weight: 700;
      }
      .text_phone {
        font-size: 32rpx;
        color: #808080;
      }
      .check_img {
        width: 40rpx;
        height: 40rpx;
        image {
          width: 100%;
          height: 100%;
        }
      }
      &--agreement {
        width: calc(100% - 80rpx);
        margin-left: 30rpx;
        text {
          font-size: 32rpx;
          // line-height: 1.2;
        }
      }
      .btn {
        width: 100%;
        color: #ffffff;
        background: #00adad;
        border-radius: 100rpx;
        font-size: 36rpx;
        padding: 30rpx;
        text-align: center;
        margin: 80rpx 0 30rpx 0;
      }
      .un_login {
        color: #aaaaaa;
        text-align: center;
        margin-top: 20rpx;
        margin-bottom: 30rpx;
      }
    }
  }
  .btns {
    display: flex;
    align-items: center;
    .btn {
      padding: 24rpx;
      font-size: 34rpx;
    }
    .btn_cancel {
      border: 1px solid var(--main-color);
      color: var(--main-color);
      background: #ffffff;
    }
    .btn_save {
      margin-left: 30rpx;
    }
  }
  .sms {
    .code {
      width: calc(100% - 200rpx);
    }
    .time {
      width: 200rpx;
      text-align: right;
    }
  }
}
</style>
